const jwt = require('jsonwebtoken')

SECRET = "shuofeng-secret"
ALGORITHM = "HS256"
AUTHORIZATION_PREFIX = "Bearer ";
EXPIRES_IN = 3600 * 1000;

// 解决BigInt value can't be serialized in JSON
// 提供一个BigInt.prototype.toJSON方法，每当 BigInt 值字符串化时都会调用该方法
BigInt.prototype.toJSON = function () {
    return Number(this);
};

const generateToken = (payload) => {
    const token = jwt.sign(payload,
        SECRET,
        {
            algorithm: ALGORITHM,
            expiresIn: EXPIRES_IN
        })
    return AUTHORIZATION_PREFIX + token;
}

const verifyToken = (token) => {
    return jwt.verify(token, SECRET)
}

module.exports = {
    SECRET,
    ALGORITHM,
    EXPIRES_IN,
    generateToken,
    verifyToken
}